package com.zimmur.alipay.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.zimmur.alipay.aliconfig.AlipayMethodEnum;
import com.zimmur.common.PropertiesCommon;

public class AlipayClientUtil {

	private static Logger log=LoggerFactory.getLogger(AlipayClientUtil.class);
	
	private static String URL="https://openapi.alipay.com/gateway.do";
	//private static String URL="https://openapi.alipaydev.com/gateway.do";
	private static String APP_ID=PropertiesCommon.getProperty("alipay.appid");
	private static String APP_PRIVATE_KEY=PropertiesCommon.getProperty("aliapp.privatekey");
	private static String FORMAT="json";
	private static String CHARSET="utf-8";
	private static String ALIPAY_PUBLIC_KEY=PropertiesCommon.getProperty("alipay.publickey");
	private static String SIGN_TYPE="RSA2";
	private final static String aliNotifyUrl=PropertiesCommon.getProperty("alipay.notifyUrl");
	private final static String aliReturnUrl=PropertiesCommon.getProperty("alipay.returnUrl");
	
	private static final AlipayClient client = new DefaultAlipayClient( 
						URL, APP_ID, APP_PRIVATE_KEY, FORMAT, 
			CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE); 
		  
	public static AlipayClient getAlipayClientInstance() { 
		    return client; 
	}

	/**
	* <p>Title: toPay</p>
	* <p>Description: 支付</p>
	*/
	public static String toPay(long trade_no,String order_je,String subject,String orderDetail,AlipayMethodEnum method) {
		String orderString=null;
		
		AlipayClient alipayClient = getAlipayClientInstance();
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
		AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
		model.setBody(orderDetail);
		model.setSubject(subject);
		model.setOutTradeNo(trade_no+"");
		model.setTimeoutExpress("30m");
		model.setTotalAmount(order_je);
		model.setProductCode(method.getMethod());
		if(method == AlipayMethodEnum.PC || method == AlipayMethodEnum.H5){
			alipayRequest.setReturnUrl(aliReturnUrl);
		}
		alipayRequest.setNotifyUrl(aliNotifyUrl);
		alipayRequest.setBizModel(model);
		
		try {
			orderString = alipayClient.pageExecute(alipayRequest).getBody();
		} catch (AlipayApiException e) {
			log.error(e.getMessage());
		}
		return orderString;
	}
}
